<template>
    <div class="tree-wrap max-w-5xl">
        <div class="tree relative overflow-auto">
            <template v-for="(edge,index) in edges">
                <course-tree-edge :edge="edge" :node="node" :key="index"></course-tree-edge>
            </template>
            <div class="step flex" v-for="step in steps" :style="{height: node.height+node.border*2+'px'}">
                <template v-for="course in step">
                    <course-tree-node :course="course" :node="node" :key="course.id"
                                      :career="$route.query.career||$route.params.skill||career"
                                      :skill="$route.query.skill||$route.params.skill||skill"></course-tree-node>

                </template>
            </div>
        </div>
    </div>
</template>

<script>
    import CourseTreeEdge from './CourseTreeEdge'
    import CourseTreeNode from './CourseTreeNode'

    export default {
        props: {
            courses: {required: true, career: [String, Number], skill: [String, Number]}
        }, components: {CourseTreeEdge, CourseTreeNode}, data() {
            return {node: {height: 120, width: 250, border: 0, padding: 10}}
        }, computed: {
            steps() {
                let steps = _.groupBy(this.courses, 'pivot.step');
                let lastStep = _.findLastKey(steps);
                let stepsArr = [];
                for (let i = 0; i <= lastStep; i++) {
                    if (steps[i]) {
                        stepsArr[i] = steps[i];
                    } else {
                        stepsArr[i] = [];
                    }
                }

                return stepsArr;
            }, edges() {
                let arr = [];
                let steps = this.steps;
                //需要先查出所有课程的step和index
                let courseStepInfo = {};

                steps.forEach((courses, step) => {
                    courses.forEach((course, index) => {
                        courseStepInfo[course.id] = {step: step, index: index};
                    });
                });
                steps.forEach((courses, step) => {
                    courses.forEach((course, index) => {
                        if (course.pivot.next_course_id) {
                            course.pivot.next_course_id.forEach(nextCourseId => {
                                arr.push({
                                    from_step: step,
                                    from_index: index,
                                    to_step: courseStepInfo[nextCourseId].step,
                                    to_index: courseStepInfo[nextCourseId].index
                                });
                            })
                        }
                    });
                });

                return arr;
            }
        }, created() {
            // console.log(this.edges);
        }
    }
</script>

<style scoped>

</style>